#import "SettingsController.h"

@interface SettingsController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *usernameTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UITextField *urlTextField;
@property (weak, nonatomic) Settings* settings;
@end

@implementation SettingsController

@synthesize usernameTextField;
@synthesize passwordTextField;
@synthesize urlTextField;
@synthesize settings;

-(void)viewWillAppear:(BOOL)animated {
    [self revertTapped];
}

- (IBAction)saveTapped {
    [self.usernameTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
    [self.urlTextField resignFirstResponder];
    
    NSError* error;
    BOOL result = [self.settings setUsername:self.usernameTextField.text password:self.passwordTextField.text url:self.urlTextField.text error:&error];
    if (error) {
        [[[UIAlertView alloc] initWithTitle:@"Erro de Login" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
    } else if (!result) {
        [[[UIAlertView alloc] initWithTitle:@"Login Inválido" message:@"Usuário ou senha incorretos." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
    } else {
        [[[UIAlertView alloc] initWithTitle:@"Login Salvo" message:@"Suas informações foram salvas." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
    }
}

- (IBAction)revertTapped {
    [usernameTextField resignFirstResponder];
    [passwordTextField resignFirstResponder];

    self.usernameTextField.text = self.settings.username;
    self.passwordTextField.text = self.settings.password;
    self.urlTextField.text = self.settings.url;
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

@end
